// 导入数据库操作模块
const db = require('../../db/index')

const fs = require('fs')
const path = require('path')
const { resolve } = require('path/posix')
const { reject, forEach } = require('async')
const { calculateCurrentSeason, getCurrentTime, calculateSolarTerm } = require('../../utils/user')
const configFile = path.resolve(__dirname, '../../../data/works商.json')
// const configFile = path.resolve(__dirname, '../../../data/works周.json')
// const configFile = path.resolve(__dirname, '../../../data/works秦.json')
// const configFile = path.resolve(__dirname, '../../../data/works汉.json')
// const configFile = path.resolve(__dirname, '../../../data/works三国.json')
// const configFile = path.resolve(__dirname, '../../../data/works晋.json')
// const configFile = path.resolve(__dirname, '../../../data/works南北朝.json')
// const configFile = path.resolve(__dirname, '../../../data/works隋.json')
// const configFile = path.resolve(__dirname, '../../../data/works唐.json')
// const configFile = path.resolve(__dirname, '../../../data/works五代十国.json')
// const configFile = path.resolve(__dirname, '../../../data/works辽.json')
// const configFile = path.resolve(__dirname, '../../../data/works宋.json')
// const configFile = path.resolve(__dirname, '../../../data/works金.json')
// const configFile = path.resolve(__dirname, '../../../data/works元.json')
// const configFile = path.resolve(__dirname, '../../../data/works明.json')
// const configFile = path.resolve(__dirname, '../../../data/works清.json')
console.log('configFile', configFile)
/*
    "Id": 11763,
    "Title": "垓下歌",
    "Dynasty": "秦",
    "Author": "项羽",
    "AuthorId": 10385,
    "Kind": "诗",
    "Content": "力拔山兮气盖世。时不利兮骓不逝。\r\n骓不逝兮可奈何！虞兮虞兮奈若何！",
    "Translation": "力可拔山啊气可盖世，可时运不济宝马也再难奔驰；\r\n宝马不奔驰啊，还有什么办法？虞姬呀！虞姬呀！我该如何安排你？",
    "Comment": "",
    "Intro": "《垓下歌》是西楚霸王项羽败亡之前吟唱的一首诗，是足以惊神泣鬼的一首壮歌。抒发了项羽在汉军的重重包围之中那种充士怨愤和无可奈何的心情。",
    "Annotation": "兮：文言助词，相当于现代的「啊」或「呀」\r\n奈何：怎么办。\r\n若：你。",
    "PostsCount": 73
*/

// 处理JSON文件
// exports.getPoetryConfig = (req, res) => {
//     const data = fs.readFileSync(configFile, 'UTF-8').toString()
//     let config = JSON.parse(data)
//     let arrConfig = []
//     let arrConfig1 = []
//     for(item of config) {
//         arrConfig1.push(item)
//         if(item.Translation || item.Annotation || item.Comment || item.Intro || item.PostsCount != 0) {
//             arrConfig.push(item)
//         }
//     }
//     // let config1 = arrConfig.slice(120000, config.length)
//     console.log('arrConfig', arrConfig.length)
//     console.log('arrConfig1', arrConfig1.length)
// }

// 获取全部作者信息(JSON)
exports.getPoetryConfig = (req, res) => {
    try {
        const data = fs.readFileSync(configFile, 'UTF-8').toString()
        let config = JSON.parse(data)
        let arrConfig = []
        let arrConfig1 = []
        for(item of config) {
            arrConfig1.push(item)
            // arrConfig1.push(item)
            if(item.Translation || item.Annotation || item.Comment || item.Intro) {
                if(item.PostsCount != 0) {
                    arrConfig.push(item)
                }
            }
        }
        console.log('arrConfig1', arrConfig1.length)
        console.log('arrConfig', arrConfig.length)
        // let config1 = arrConfig.slice(0, config.length)
        // // let config1 = arrConfig.slice()
        // console.log(config1.length)
        // let arr = []
        // let promiseArr = []
        // config1.forEach((item, index) => {
        //     promiseArr.push(new Promise((resolve, reject) => {
        //         const selectSql = `select * from author where author_id=${item.AuthorId}`
        //         db.query(selectSql, (err, selectres) => {
        //             if(err) resolve('失败')
        //             else if(selectres.length != 0) {
        //                     let obj = []
        //                     obj.push(`${item.Dynasty}`) // 朝代
        //                     obj.push(`${item.AuthorId}`) // 作者id
        //                     obj.push(`${item.Title}`) // 标题
        //                     obj.push(`${item.Content}`) // 内容
        //                     obj.push(`${item.Intro}`) // 赏析/介绍
        //                     obj.push(`${item.Translation}`) // 译文
        //                     obj.push(`${item.Comment}`) // 评价
        //                     obj.push(`${item.Annotation}`) // 字词翻译
        //                     obj.push(`${item.Kind}`) // 类型
        //                     obj.push(item.PostsCount) // 点击量
        //                     obj.push(1) // 状态
        //                     arr.push(obj)
        //                     resolve('1')
        //             } else {
        //                 resolve(`${item.AuthorId}`)
        //             }
        //         })
        //     }))
        // })
        // // console.log()
        // Promise.all(promiseArr).then(promiseRes => {
        //     console.log('arr.len', arr.length)
        //     console.log('promiseRes', promiseRes)
        //     const insertSql = `insert into poetry2(p_dynasty, aid, p_title, p_content, p_analyze, p_translation, p_comment, p_annotation, p_genre, p_postscount, p_state) values ?`
        //     // const insertSql = `insert into poetry2(aid) values ('10385')`
        //     db.query(insertSql, [arr] , (err, insertRes) => {
        //         if(err) return res.operationSuccess('failure', 'ERR051', '添加诗词信息失败！', err)
        //         return res.operationSuccess('success', '', '添加诗词信息成功！', [])
        //     })
        // })
    } catch (error) {
        console.log('get_config.error', error)
    }
}

// 获取诗歌信息   (不获取p_state为0的诗歌)
exports.getPoetry = (req, res) => {
    const { pageNum, pageSize } = req.body
    let starNum = (pageNum - 1) * pageSize
    // const sql1 = `select count(distinct(pid)) as total from poetry2 p, author a where a.author_id=p.aid and p.p_state=1`
    const sql1 = `select count(*) as total from poetry2 p where p.p_state=1`
    // const sql1 = `select count as total from table_rows where table_name='poetry2`
    const sql2 = `select p.pid, p.aid, a.a_name, p.p_title, p.p_dynasty, p.p_content, p.p_analyze, p.p_translation, p.p_comment, p.p_annotation, p.p_genre, p.p_postscount, p.p_cover from poetry2 p, author a where a.author_id = p.aid and p.p_state=1 limit ${starNum}, ${pageSize}`
    db.query(sql1, (err, results1) => {
        if(err) return res.operationSuccess('failure', 'ERR050', '获取诗歌信息失败！', err)
        db.query(sql2, (err, results2) => {
            if(err) return res.operationSuccess('failure', 'ERR050', '获取诗歌信息失败！', err)
            return res.operationSuccess('success', '', '获取诗歌信息成功！', {total: results1[0].total, results2: results2})
        })
    })
}

// 添加诗歌信息
exports.addPoetry = (req, res) => {
    const { aid, p_title, p_dynasty, p_content, p_analyze, p_translation, p_comment, p_annotation, p_genre, p_cover, addLidString } = req.body 
    const sql1 = `insert into poetry2(aid, p_title, p_dynasty, p_content, p_analyze, p_translation, p_comment, p_annotation, p_genre, p_cover, p_postscount, p_state) values('${aid}', '${p_title}', '${p_dynasty}', '${p_content}', '${p_analyze}', '${p_translation}', '${p_comment}', '${p_annotation}', '${p_genre}', '${p_cover}', 0, 1)`
    db.query(sql1, (err, results) => { 
        if(err) return res.operationSuccess('failure', 'ERR051', '添加诗歌信息失败！', err)
        console.log('err', err)
        if(addLidString != '') {
            let arr = []
            addLidString.toString().split(',').forEach((item) => {
                let arr1 = []
                arr1.push(`${results.insertId}`)
                arr1.push(`${item}`)
                arr1.push(1)
                arr.push(arr1)
            })
            const sql2 = `insert into poetry_label(pid, lid, pl_state) values ?`
            db.query(sql2, [arr], (err2, results2) => { 
                console.log(err2)
                if(err2) return res.operationSuccess('failure', 'ERR086', '添加诗歌信息成功但是根据pid添加诗歌标签信息失败！', err2)
                return res.operationSuccess('success', '', '添加诗歌信息成功！', [])
            })
        } else return res.operationSuccess('success', '', '添加诗歌信息成功！', [])
    })
}

// 根据id删除诗歌信息
exports.deletePoetryById = (req, res) => {
    const { pid } = req.body
    console.log('pid', pid)
    const sql = `update poetry2 set p_state=0 where pid in (${ pid })`
    // const sql = `delete from poetry2 where pid in (${ pid })`
    db.query(sql, (err, results) => {
        if(err) return res.operationSuccess('failure', 'ERR052', '删除诗歌信息失败！', err)
        return res.operationSuccess('success', '', '删除诗歌信息成功！', [])
    })
}

// 根据诗歌名称/诗句/朝代/诗人查找诗歌信息
exports.searchPoetryByNameOrVerseDynastyOrAuthor = (req, res) => {
    // let { did } = req.body
    // const selectSql = `select * from poetry2 where did=${ did } and d_state=1`
    // db.query(selectSql, (err, selectRes) => {
    //     if(err) return res.operationSuccess('failure', 'ERR045', '查找诗歌失败！', err)
    //     return res.operationSuccess('success', '', '查找诗歌成功！', selectRes)
    // })
    const { searchType, searchText, pageNum, pageSize } = req.body
    let starNum = (pageNum-1) * pageSize
    // 判断用户是根据名称还是时间查询
    // N 为根据诗歌名称， v 为根据诗句查询， D 为根据朝代查询， A 为根据诗人查询
    let type = ''
    // searchType == 'N' ? type = 'd.d_name' : type = 'a.a_name' 
    searchType == 'N' ? type = 'p.p_title' : (searchType == 'V' ? type = 'p.p_content' : searchType == 'D' ? type = 'p.p_dynasty' : type = 'a.a_name')
    // 1 代表未删除  0代表删除
    // const sql = `select a.author_id, a.a_name, a.a_synopsis, a.a_time, d.d_name from author a, dynasty d where a.did=d.did and ${type} like '%${searchText}%' and a.a_state=1 limit ${starNum}, ${pageSize}`
    let string = ''
    if(pageNum && pageSize) {
        string = `limit ${starNum}, ${pageSize}`
    }
    // const sql1 = `select count(distinct(pid)) as total from poetry2 p, author a where a.author_id=p.aid and ${type} like '%${searchText}%'`
    const sql1 = `select count(*) as total from poetry2 p, author a where a.author_id=p.aid and ${type} like '%${searchText}%'`
    const sql2 = `select p.pid, p.aid, a.a_name, p.p_title, p.p_dynasty, p.p_content, p.p_analyze, p.p_translation, p.p_comment, p.p_annotation, p.p_genre, p.p_postscount, p.p_cover from poetry2 p, author a where a.author_id = p.aid and p.p_state=1 and ${type} like '%${searchText}%' ${string}`
    console.log(sql2)
    db.query(sql1, (err, results1) => {
        if (err) return res.operationFailed(err)
        db.query(sql2, (err, results2) => {
            if (err) return res.operationSuccess('failure', 'ERR053', '查找诗歌信息失败！', err)
            return res.operationSuccess('success', '', '查找诗歌信息成功！', {total: results1[0].total, results2: results2})
        })
    })
}

// 根据id修改诗歌信息
exports.updatePoetryById = (req, res) => {
    // const { pid, aid, p_title, p_dynasty, p_content, p_analyze, p_translation, p_comment, p_annotation, p_genre, p_cover } = req.body
    // const { pid, aid, p_title, p_dynasty, p_content, p_analyze, p_translation, p_comment, p_annotation, p_genre, p_cover, addLidString, deleteLidString } = req.body
    const { poetryInfo, addLidString, deleteLidString } = req.body
    // console.log('body', req.body)
    const { pid, aid, p_title, p_dynasty, p_content, p_analyze, p_translation, p_comment, p_annotation, p_genre, p_cover } = JSON.parse(poetryInfo) 
    const selectSql = `select * from poetry2 where pid='${ pid }'`
    // console.log('pid', selectSql)
    db.query(selectSql, (err1, selectRes) => {
        if(err1) return res.operationSuccess('failure', 'ERR053', '查找诗歌信息失败！', err1)
        let author_id = aid !== '' ? aid : selectRes[0].aid
        let title = p_title !== '' ? p_title : selectRes[0].p_title
        let dynasty = p_dynasty !== '' ? p_dynasty : selectRes[0].p_dynasty
        let content = p_content !== '' ? p_content : selectRes[0].p_content
        let analyze = p_analyze
        let translation = p_translation
        let comment = p_comment
        let annotation = p_annotation
        let genre = p_genre
        let cover = p_cover
        let sql = ''
        const updateSql = `update poetry2 set aid='${ author_id }', p_title='${ title }', p_dynasty='${ dynasty }', 
                    p_content='${ content }', p_analyze='${ analyze }', p_translation='${ translation }', p_comment='${ comment }', 
                    p_annotation='${ annotation }', p_genre='${ genre }', p_cover='${ cover }' where pid='${ pid }'`
        console.log(updateSql)
        sql += `${updateSql};`
        console.log('deleteLidString', deleteLidString)
        let deleteSql = `delete from poetry_label where pid=${pid} and lid in (${deleteLidString})`
        let insertSql = `insert into poetry_label(pid, lid, pl_state) values ?`
        if(deleteLidString != '') sql += `${deleteSql};`
        let arr = []
        if(addLidString != '') {
            sql += `${insertSql}`
            addLidString.toString().split(',').forEach((item) => {
                let arr1 = []
                arr1.push(`${pid}`)
                arr1.push(`${item}`)
                arr1.push(1)
                arr.push(arr1)
            })
        }
        console.log('sql', sql)
        db.query(sql, [arr], (err2, selectRes) => {
            console.log(err2)
            if(err2) return res.operationSuccess('failure', 'ERR054', '更改诗歌信息失败！', err2)
            return res.operationSuccess('success', '', '更改诗歌信息成功！', [])
        })
    })
}

// 根据id获取诗歌信息
exports.getPoetryByPid = (req, res) => {
    const { pid } = req.query
    // const sql = `select * from label l left join poetry_label pl on pl.pid=p.pid where p.pid=${pid} `
    const sql1 = `select * from poetry2 p, author a where p.pid=${pid} and p.aid=a.author_id`
    const sql2 = `select * from poetry2 p, label l, poetry_label pl where p.pid=${pid} and p.pid=pl.pid and l.lid=pl.lid`
    db.query(`${sql1};${sql2}`, (err, result) => {
        if(err) return res.operationSuccess('failure', 'ERR056', '根据pid获取诗歌信息失败！', err)
        let obj = {poetry: {...result[0][0]}, label: result[1]}
        return res.operationSuccess('success', '', '根据pid获取诗歌信息成功！', obj)
    })
}

// 根据标签获取诗歌信息
exports.getPoetryByLid = (req, res) => {
    const { lid } = req.query
    if(!lid) {
        // 获取当前节气
        let date = getCurrentTime('date').split('/')
        let solarTerm = calculateSolarTerm(date[0], date[1], date[2])
        // 获取当前季节
        let currentMonth = calculateCurrentSeason()
        // 随机一个主题
        // let selectThemeSql = `select * from type t left join label l on t.tid=l.tid LEFT JOIN poetry_label pl on pl.lid=l.lid LEFT JOIN poetry2 p on pl.pid=p.pid where t.tid=1`
        let selectLabelSql = `select * from type t, label l where t.tid=l.tid and t.t_name='主题' and t.t_state=1 and l.l_state=1`
        new Promise((resolve,reject) => {
            db.query(selectLabelSql, (slErr, slRes) => {
                if(slErr) return res.operationSuccess('failure', 'ERR081', '获取分类标签信息失败！', slErr)
                resolve(slRes)
            })
        }).then(slRes => {
            let random = Math.floor(Math.random() * slRes.length)
            let theme = slRes[random]
            // let theme = slRes[0]
            console.log('theme', theme.l_name)
            let l_name = `'${currentMonth}','${solarTerm}','${theme.l_name}'`
            let sql = `select * from poetry2 p, label l, poetry_label pl where p.p_state=1 and l.l_state=1 and pl.pl_state=1 and pl.pid=p.pid and pl.lid=l.lid and l.l_name in (${l_name})`
            db.query(sql, (selecErr, selectRes) => {
                if(selecErr) return res.operationSuccess('failure', 'ERR055', '根据标签获取诗歌信息失败！', [])
                let obj = {
                    solarTerm: {type: solarTerm, lid: '', items: []},
                    month: {type: currentMonth, lid: '', items: []},
                    theme: {type: theme.l_name, lid: '', items: []}
                }
                if(selectRes.length != 0) {
                    selectRes.forEach((item, index) => {
                        if(item.tid == 9) {
                            obj.month.lid = item.lid
                            obj.month.items.push(item)
                        } else if(item.tid == 5) {
                            obj.solarTerm.lid = item.lid
                            obj.solarTerm.items.push(item)
                        } else if(item.tid == 1) {
                            obj.theme.lid = item.lid
                            obj.theme.items.push(item)
                        }
                    })
                }
                return res.operationSuccess('success', '', '根据标签获取诗歌信息成功！', obj)
            })
        })
    } else {
        // let selectSql = `select * from poetry2 p, label l, poetry_label pl where p.p_state=1 and l.l_state=1 and pl.pl_state=1 and pl.pid=p.pid and pl.lid=l.lid and l.lid=${lid}`
        // let selectSql = `select * from type t left join label l on t.tid=l.tid LEFT JOIN poetry_label pl on pl.lid=l.lid LEFT JOIN poetry2 p on pl.pid=p.pid left join author a on p.aid=a.author_id where l.lid=${lid}`
        let selectSql = `select * from poetry_label pl LEFT JOIN poetry2 p on pl.pid=p.pid left join author a on p.aid=a.author_id left join label l on pl.lid=l.lid left join type t on t.tid=l.tid where l.lid=${lid}`
        db.query(selectSql, (selecErr, selectRes) => {
            if(selecErr) return res.operationSuccess('failure', 'ERR055', '根据标签获取诗歌信息失败！', [])
            let arr = selectRes
            let obj = {}
            if(selectRes.length != 0) {
                obj = { type: selectRes[0].l_name, lid: selectRes[0].lid, cover: selectRes[0].l_cover, items: arr }
                return res.operationSuccess('success', '', '根据标签获取诗歌信息成功！', obj)
            } else {
                let selectSql2 = `select l.*, t.* from label l, type t where l.lid=${lid} and t.tid=l.tid`
                db.query(selectSql2, (selecErr2, selectRes2) => { 
                    console.log('selectRes2', selectRes2)
                    if(selecErr2) return res.operationSuccess('failure', 'ERR055', '根据标签获取诗歌信息失败！', [])
                    obj = { type: selectRes2[0].l_name, lid: selectRes2[0].lid, cover: selectRes2[0].l_cover }
                    return res.operationSuccess('success', '', '根据标签获取诗歌信息成功！', obj)
                })
            }
        })
    }
}

// 收藏诗歌
exports.collectPoetry = (req, res) => {
    let { pid, bp_collection } = req.body
    console.log(pid, bp_collection)
    // bp_collection ? bp_collection = 1 : bp_collection = 0
    let msg = ''
    bp_collection != 'true' ? msg = '取消收藏' : msg = '收藏成功' 
    console.log(msg)
    const { uid } = req.auth
    const selectSql = `select * from user_poetry where uid='${uid}' and pid=${pid}`
    console.log(selectSql)
    db.query(selectSql, (err1, res1) => {
        if(err1) return res.operationSuccess('failure', 'ERR057', '收藏诗歌信息失败！', err1)
        if(res1.length == 0) {
            const insertSql = `insert into user_poetry(uid, pid, bp_collection) values('${uid}', ${pid}, 1)`
            db.query(insertSql, (err2, res2) => {
                if(err2) return res.operationSuccess('failure', 'ERR057', '收藏诗歌信息失败！', err2)
                return res.operationSuccess('success', '', '收藏诗歌成功', {message: msg})
            })
        } else {
            const insertSql = `update user_poetry set bp_collection=${bp_collection} where uid='${uid}' and pid=${pid}`
            db.query(insertSql, (err3, res3) => {
                if(err3) return res.operationSuccess('failure', 'ERR057', '收藏诗歌信息失败！', err3)
                return res.operationSuccess('success', '', '收藏诗歌成功', {message: msg})
            })
        }
    })
}

// 查询收藏信息
exports.queryCollectPoetryInfo = (req, res) => {
    let { pid } = req.query
    const { uid } = req.auth
    const selectSql = `select * from user_poetry where uid='${uid}' and pid=${pid}`
    db.query(selectSql, (err1, res1) => {
        if(err1) return res.operationSuccess('failure', 'ERR058', '查询收藏信息失败！', err1)
        return res.operationSuccess('success', '', '查询收藏信息成功', res1)
    })
}